<script setup>
import http from "@/utils/http.js";
import {onMounted, ref} from "vue";

const swipeRef = ref(null)
// const imageUrls = [
//     'https://pic1.zhimg.com/v2-02760a1bf058904006740d3f66b2c9ac_r.jpg?source=1940ef5c',
//     'https://pic1.zhimg.com/v2-02760a1bf058904006740d3f66b2c9ac_r.jpg?source=1940ef5c',
//     'https://pic1.zhimg.com/v2-02760a1bf058904006740d3f66b2c9ac_r.jpg?source=1940ef5c'
// ]
const imageUrls =ref([])
const getPhoto = async () => {
  const res = await http.get('/goods/photo')
  imageUrls.value = res.data
}

onMounted(() => {
  getPhoto()
})



//左右箭头的方法，对于<van-swipe>来说，它有.next() .prev()方法
const prevP = () => {
    if (swipeRef.value) {
        swipeRef.value.prev()
    }
}

const nextP = () => {
    if (swipeRef.value) {
        swipeRef.value.next()
    }
}

const defaultImage = 'https://img.tukuppt.com/png_preview/00/11/69/840wwqEs8Z.jpg!/fw/780' // 默认图片链接

const handleImageError = (event) => {
  const imgElement = event.target
  if (!imgElement.dataset.defaultSrcLoaded) {
    imgElement.src = defaultImage
    imgElement.dataset.defaultSrcLoaded = true // 防止死循环
  }
}
</script>

<template>
    <div class="swipe-container">
        <!-- 左侧箭头 -->
        <button class="arrow left" @click="prevP">❮</button>

        <!-- 轮播图 -->
        <van-swipe ref="swipeRef" class="my-swipe" :autoplay="3000" indicator-color="white"
            :style="{ height: '300px' }">
            <van-swipe-item v-for="item in imageUrls" :key="item.goodsId">
                <img :src="item.goodsPhoto" alt="轮播图" class="slide-image" @error="handleImageError" :data-default-src="defaultImage"/>
            </van-swipe-item>
        </van-swipe>

        <!-- 右侧箭头 -->
        <button class="arrow right" @click="nextP">❯</button>
    </div>
</template>

<style scoped>
.swipe-container {
    position: relative;
    max-width: 800px;
    margin: 0 auto;
}

.my-swipe {
    border-radius: 8px;
    overflow: hidden;
}

.slide-image {
  width: 100%;
  height: auto;
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  display: block;
  margin: 0 auto;
}

.arrow {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    border: none;
    padding: 10px;
    font-size: 24px;
    cursor: pointer;
    z-index: 2;
}

.left {
    left: 10px;
}

.right {
    right: 10px;
}

.arrow:hover {
    background-color: rgba(0, 0, 0, 0.8);
}
</style>